package com.xiemulei.gulimall.auth.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.xiemulei.common.constant.AuthServerConstant;
import com.xiemulei.common.utils.HttpUtils;
import com.xiemulei.common.utils.R;
import com.xiemulei.gulimall.auth.feign.MemberFeignClient;
import com.xiemulei.common.vo.MemberResponseVo;
import com.xiemulei.common.vo.SocialUserVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Resource
    MemberFeignClient memberFeignClient;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3420717823");
        map.put("client_secret", "a0a2e88e1c928fe690d2325e6373f169");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        // 使用 code 请求 access token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "POST", new HashMap<>(), null, map);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class);
            R r = memberFeignClient.oauthLogin(socialUserVo);
            if (r.getCode() == 0) {
                MemberResponseVo data = r.getData("data", new TypeReference<>() {
                });
                log.info("登陆成功，用户：{}", data);
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
